package com.jrx.anytxn.reporting.job.xib.config;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.reporting.config.AnyTxnBatchProperties;
import com.jrx.anytxn.reporting.constant.ReportingConstant;
import com.jrx.anytxn.reporting.entity.AmlIATrading;
import com.jrx.anytxn.reporting.job.unionFile.step.UnionRepayFileReader;
import com.jrx.anytxn.reporting.job.xib.bean.AmlIATradingBean;
import com.jrx.anytxn.reporting.job.xib.step.*;
import com.jrx.anytxn.transaction.entity.AmLoanMainInfo;
import com.jrx.anytxn.transaction.entity.TlPaymentLog;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.batch.MyBatisPagingItemReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.ItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 反洗钱（放款,还款,增加利息计提，罚息计提）
 */
@Configuration
@EnableConfigurationProperties(AnyTxnBatchProperties.class)
@EnableBatchProcessing
public class MockGenerateTradingConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(MockGenerateTradingConfiguration.class);

    @Resource(name = "bizSqlSessionFactory")
    SqlSessionFactory sqlSessionFactory;

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Autowired
    private AnyTxnBatchProperties anyTxnBatchProperties;

    @Autowired
    private MockTradingListener tradingListener;

    @Autowired
    private MockTradingProcessor mockTradingProcessor;

    @Autowired
    private TradingWriter tradingWriter;

    @Autowired
    private MockTradingPaymentProcessor mockTradingPaymentProcessor;

    @Autowired
    private TradingPaymentWriter tradingPaymentWriter;

    final String MOCK_KEY = "mock.today";

    @Autowired
    Environment env;

    @Bean
    public Job mockGenerateTradingJob() {
        return jobBuilderFactory.get("mockGenerateTradingJob").incrementer(new RunIdIncrementer()).listener(tradingListener)
                .start(mockGenerateLoanStep())
                .next(mockGeneratePaymentStep())
                .build();
    }

    @Bean
    public Step mockGenerateLoanStep(){
        return stepBuilderFactory.get("mockGenerateLoanStep")
                .<AmLoanMainInfo, AmlIATrading>chunk(anyTxnBatchProperties.getReportingCustomerConfig().getChunkLimit())
                //表示一批处理100
                // 条记录，数据是逐条发送给processor处理的，处理100条记录后，统一返回给writer进行保存处理
                .reader(mockLoanReader())
                .processor(mockTradingProcessor)
                .writer(tradingWriter)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                .throttleLimit(anyTxnBatchProperties.getReportingCustomerConfig().getThrottleLimit())//多线程*/
                .build();
    }

    @Bean
    public Step mockGeneratePaymentStep(){
        return stepBuilderFactory.get("mockGeneratePaymentStep")
                .<TlPaymentLog, AmlIATradingBean>chunk(anyTxnBatchProperties.getReportingCustomerConfig().getChunkLimit())
                //表示一批处理100
                // 条记录，数据是逐条发送给processor处理的，处理100条记录后，统一返回给writer进行保存处理
                .reader(mockPaymentReader())
                .processor(mockTradingPaymentProcessor)
                .writer(tradingPaymentWriter)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                .throttleLimit(anyTxnBatchProperties.getReportingCustomerConfig().getThrottleLimit())//多线程*/
                .build();
    }

    @Bean
    @StepScope
    public MyBatisPagingItemReader<AmLoanMainInfo> mockLoanReader(){
        logger.info("抽取订单批量启动,机构号：{}", ReportingConstant.DEFAULT_ORG_NUMBER);

        //键值mock.today
        final String todayStr = env.getProperty(MOCK_KEY, String.class);
        if (StringUtils.isEmpty(todayStr)) {
            throw new RuntimeException(MOCK_KEY + "不能为空");
        } else {
            Date today = DateUtils.parseDate(todayStr, "yyyy-MM-dd");
            logger.info("查询数据业务日期："+ todayStr);
            PrOrganizationTable pot = new PrOrganizationTable();
            pot.setToday(today);
            return new LoanReader(sqlSessionFactory,anyTxnBatchProperties.getReportingLoanAcctConfig().getPageSize(), pot);
        }
    }

    @Bean
    @StepScope
    public ItemReader<TlPaymentLog> mockPaymentReader(){
        logger.info("抽取还款流水启动,机构：{}", ReportingConstant.DEFAULT_ORG_NUMBER);

        //键值mock.today
        final String todayStr = env.getProperty(MOCK_KEY, String.class);
        if (StringUtils.isEmpty(todayStr)) {
            throw new RuntimeException(MOCK_KEY + "不能为空");
        } else {
            Date today = DateUtils.parseDate(todayStr, "yyyy-MM-dd");
            logger.info("查询数据业务日期："+ todayStr);
            PrOrganizationTable pot = new PrOrganizationTable();
            pot.setToday(today);
            return new UnionRepayFileReader(sqlSessionFactory,anyTxnBatchProperties.getFileConfig().getPageSize(), pot);
        }
    }

}
